<template>
  <div>
    <a-upload
      :show-file-list="false"
      :file-list="[]"
      :limit="1"
      :before-upload="handleBeforeUpload"
      :custom-request="customRequest"
      class="w-full"
    >
      <el-input v-model="inputValue" readonly clearable placeholder="请上传范围线，只支持json格式">
        <i
          v-if="localFileList.length === 0"
          slot="suffix"
          class="el-icon-upload text-2xl pr-1 pt-[4px] cursor-pointer"
        />
        <i
          v-else
          slot="suffix"
          class="el-icon-delete-solid text-xl pr-1 pt-[4px] cursor-pointer"
          @click.stop="handleDel"
        />
      </el-input>
    </a-upload>
  </div>
</template>

<script>
import { getAuthInfo, uploadToAliOSS } from '@/api/files.ts'
export default {
  components: {},
  props: {
    fileList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {}
  },
  computed: {
    localFileList: {
      get() {
        return this.fileList
      },
      set(val) {
        this.$emit('update:fileList', val)
      },
    },

    inputValue() {
      return this.localFileList[0]?.name
    },
  },
  methods: {
    handleBeforeUpload(file) {
      console.log('%c [ file ]-62', 'font-size:13px; background:pink; color:#bf2c9f;', file)
      if (file.type !== 'application/json') {
        this.$msgbox('请上传json文件！', '提示')
        return false
      }
      return true
    },
    handleDel() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.localFileList = []
      })
    },
    async customRequest(obj) {
      const { file } = obj
      const auth = await getAuthInfo({
        bizType: '100001',
        fileOriginalName: file.name,
        isUseOriginalName: 1,
      })

      const { fileId, filePath, host } = auth
      const authInfo = { ...auth, fileId, fileName: file.name }
      const result = await uploadToAliOSS({ ...authInfo, file })
      if (result.data.Status === 'OK') {
        const newFile = {
          uid: fileId,
          name: file.name,
          status: 'done',
          url: `${host}/${filePath}`,
        }

        this.localFileList = [newFile]
      }
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .ant-upload {
  display: block;
}
</style>
